package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
@Api(tags = "菜品接口")
@SuppressWarnings(value = "all")//清除警告
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    @ApiOperation(value = "保存菜品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dishDto", value = "菜品扩展实体类")
    })
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        //调用自定义方法保存菜品和口味
        dishService.saveWithFlavor(dishDto);
        //清理某个分类下面的菜品缓存数据
        String key ="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("添加成功");
    }


    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        //获取分页构造器对象
        Page<Dish> dishPage = new Page(page, pageSize);
        //dishPage 没有categoryName属性 不能满足前端需求   所以要把属性复制到 dtoPage 中传递给前端
        Page<DishDto> dtoPage = new Page<>();

        //获取条件构造器对象
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Dish::getName, name);
        wrapper.orderByDesc(Dish::getUpdateTime);

        //调用方法查询
        dishService.page(dishPage, wrapper);

        //对象拷贝  records是需要的泛型是不一样的不能直接复制 所以需要手动复制
        BeanUtils.copyProperties(dishPage, dtoPage, "records");

        //获取dishInfo 的records 复制给dishDtoPage 的records  并给categoryName 赋值
        List<Dish> records = dishPage.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            //网页需要展示 categoryName 分类名称这个属性 而两个实体类中都没有 所以在DishDto中设置
            DishDto dishDto = new DishDto();
            //复制 dishPage中的records      到dtoPage 中的records
            BeanUtils.copyProperties(item, dishDto);

            //获取菜品ID
            Long categoryId = item.getCategoryId();
            //根据ID查询分类
            Category category = categoryService.getById(categoryId);
            //获取菜品分类名称
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        log.info("id={}", id);

        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {

        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);
        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key
        return R.success("保存成功");
    }

    /**
     * 根据菜品分类查询菜品
     *
     * @param dish
     * @return
     */
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish) {

        //条件构造器
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());

        wrapper.like(dish.getName()!=null,Dish::getName,dish.getName());
        //添加条件，查询状态为1（起售状态）的菜品
        wrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //根据菜品id查询菜品
        List<Dish> list = dishService.list(wrapper);

        return R.success(list);
    }*/

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtoList=null;
        //定义key
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //先在缓存中查找
        dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList!=null){
            //缓存中有,直接返回
            return R.success(dishDtoList);
        }

        //条件构造器
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());

        wrapper.like(dish.getName()!=null,Dish::getName,dish.getName());
        //添加条件，查询状态为1（起售状态）的菜品
        wrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //根据菜品id查询菜品
        List<Dish> list = dishService.list(wrapper);
        dishDtoList = list.stream().map((item) -> {
            //网页需要展示 categoryName 分类名称这个属性 而两个实体类中都没有 所以在DishDto中设置
            DishDto dishDto = new DishDto();
            //复制 dishPage中的records      到dtoPage 中的records
            BeanUtils.copyProperties(item, dishDto);

            //获取菜品ID
            Long categoryId = item.getCategoryId();
            //根据ID查询分类
            Category category = categoryService.getById(categoryId);
            //获取菜品分类名称
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //设置dishDto 中的口味
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,item.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);

            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        //缓存中没有,添加到缓存
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }


    /**
     * 根据id修改状态
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/0")
    public R<String> status(Long[] ids) {
        /*LambdaQueryWrapper <Dish> wrapper=new LambdaQueryWrapper<>();
        //设置查询条件
        wrapper.in(Dish::getId,ids);
        Dish dish=new Dish();
        dish.setStatus(0);
        dishService.update(dish,wrapper);*/

        //update dish set status=1 where id in(ids)
        LambdaUpdateWrapper<Dish> wrapper=new LambdaUpdateWrapper<>();
        //设置修改条件
        wrapper.in(Dish::getId,ids);
        //设置修改内容
        wrapper.set(Dish::getStatus,0);
        //调用修改方法
        dishService.update(wrapper);
        return R.success("修改成功");
    }

    /**
     * 根据id修改状态
     * @param ids
     * @return
     */
    @PostMapping("/status/1")
    public R<String> status1(Long[] ids) {
        /*LambdaQueryWrapper <Dish> wrapper=new LambdaQueryWrapper<>();
        wrapper.in(Dish::getId,ids);
        Dish dish=new Dish();
        dish.setStatus(1);
        dishService.update(dish,wrapper);*/

        //update dish set status=1 where id in(ids)
        //修改构造器
        LambdaUpdateWrapper<Dish> wrapper=new LambdaUpdateWrapper<>();
        //设置修改条件
        wrapper.in(Dish::getId,ids);
        //设置修改内容
        wrapper.set(Dish::getStatus,1);
        //调用修改方法
        dishService.update(wrapper);
        return R.success("修改成功");
    }

    /**
     * 根据id删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long>ids){

        dishService.deleteWithFlavor(ids);

        return R.success("删除成功");
    }
}
